import Moment from 'moment';
// import api from '@api/api';
import userapi from "@/api/userConfig";
/**
 * getXAxis（）方法作用：获取开始日期和结束日期之间（包含开始日期和结束日期）的日期数组，可作为时间轴坐标等
 * @param  filters: {tab:0/1/2, startTime:开始日期, endTime:结束日期}
 * 说明： tab：取值0或1或2，分别表示日、月、年，对应的startTime和endTime的格式分别为'YYYY-MM-DD'、'YYYY-MM'、'YYYY'
 */

function buildDateAxis(parames) {
    let { timeFormat, startTime, endTime } = parames;
    // 计算两个日期之间间隔的天数,月数,年数
    let length = 0; //日期跨度变量

    if (timeFormat == 'days') {
        length = Moment(endTime).diff(Moment(startTime), 'days');
    } else if (timeFormat == 'months') {
        length = Moment(endTime).diff(Moment(startTime), 'months');
    } else if (timeFormat == 'years') {
        length = Moment(endTime).diff(Moment(startTime), 'years');
    }

    let xAxis = new Array(length + 1);

    for (let index = 0; index < xAxis.length; index++) {
        if (timeFormat == 'days') {
            xAxis[index] = Moment(startTime)
                .add(index, 'days')
                .format('YYYY-MM-DD');
        } else if (timeFormat == 'months') {
            xAxis[index] = Moment(startTime)
                .add(index, 'months')
                .format('YYYY-MM');
        } else if (timeFormat == 'years') {
            xAxis[index] = Moment(startTime)
                .add(index, 'years')
                .format('YYYY');
        }
    }

    return xAxis;
}

/**
 * 根据X坐标数组生成对应的Y坐标数组
 * @param  xArr: 上面getXAxis()方法返回的X坐标（时间轴坐标）数组;
 *  list:[{xAxis:"2017-03-01", yAxis:"200"},{xAxis:"2017-03-02", yAxis:"100"},...]  后台返回的坐标点数组，按时间升序排列
 */

function buildYAxis(xArr, list) {
    var len = xArr.length;
    var yAxis = new Array(len);
    var j = 0;
    listLen = list.length;
    for (i in xArr) {
        if (j < listLen && xArr[i] == list[j].xAxis) {
            yAxis[i] = list[j].yAxis;
            j++;
        } else {
            yAxis[i] = 0;
        }
    }

    return yAxis;
}

// 1.用于判断当前变量的值是否为 null 或 undefined 类型。
function isNull(val) {
    return val == undefined || val == null;
}

// 2.用于检查当前的值是否为数字类型。
function isNumber(val) {
    return !isNaN(parseFloat(val)) && isFinite(val);
}

// 3.用于判断参数的值是否是对象
function isObject(val) {
    return val == Object(val);
}

// 4.用于检查当前的值是否为字符串类型。
function isString(val) {
    return val != undefined && val != null && val != '' && typeof val === 'string';
}

// 5.用于检查当前的值是否为数组。
function isArray(val) {
    if (Array.isArray) {
        return Array.isArray(val);
    } else {
        return Object.prototype.toString.call(val) == '[object Array]';
    }
}

// 6.用于判断参数的值是否是 Symbol 类型。
function isSymbol(val) {
    return typeof val === 'symbol';
}

function buildLinkSelect(lists, lv1key, lv2Key) {
    let lv1 = buildSelectOption(lists, lv1key);
    let lv2 = buildSecondSelectOption(lists, lv1key, lv2Key);
    return {
        lv1,
        lv2,
    };
}

function buildSelectOption(lists, lv1key) {
    let _lists = [];
    _lists = lists.map((item, index) => {
        return {
            label: item[lv1key],
            value: item[lv1key],
        };
    });
    return _lists;
}

function buildSecondSelectOption(lists, lv1Key, lv2Key) {
    let listsObj = {};
    lists.forEach((item, index) => {
        listsObj[item[lv1Key]] = item[lv2Key].map((item2, index2) => {
            return {
                label: item2,
                value: item2,
            };
        });
    });
    return listsObj;
}

function formatPictureIds(lists) {
    let idLists = [];
    if (lists.length > 0) {
        lists.forEach((item, index) => {
            idLists.push(item.uid);
        });
        return idLists;
    } else {
        return [];
    }
}

async function initUserInfo(_this) {
    _this.userName = localStorage.getItem('userName');
    if (!_this.userName) {
        _this.$router.push('/');
    } else {
        return new Promise(async(resolve, reject) => {
            const res = await userapi.getRoleId({ phoneNumber: _this.userName });
            if (res.MsgCode !== 0) {
                _this.$message.error('获取用户信息失败');
                reject('getRoleId erroe');
            } else {
                _this.name = res.Data.name;
                _this.role = res.Data.ID;
                _this.compId = res.Data.compid;
                _this.userInfo = res.Data;
                resolve();
            }
        });
    }
}

// 根据登陆的手机号获取角色id;该方法适用于子组件获取user信息
function getRoleId(_this) {
    _this.userName = localStorage.getItem('phone');
    let { ID, compid, name } = JSON.parse(localStorage.getItem('userInfo'));
    _this.name = name;
    _this.role = ID;
    _this.compId = compid;
}

// 下拉框组件过滤用的函数
function filterSelectLists(input, option) {
    let str = input.replace(/\s*/g, '');
    let name = option.componentOptions.children[0].text;

    if (name == '' || name == undefined || str == '' || str == undefined) {
        return false;
    } else {
        let isMatch = name.indexOf(str) >= 0;
        return isMatch;
    }
}

//数普通对象转key-value对象
function formatObjectToObject(lists) {
    // for (const key in object) {
    //   if (Object.hasOwnProperty.call(object, key)) {
    //     const element = object[key];
    //   }
    // }
    // return Object.keys(obj).map((val, index) => {
    //   obj[val]; // 可以针对obj的不同属性做不同处理
    // });
    // let dataLists = [];
    // for (const key in resData) {
    //   if (Object.hasOwnProperty.call(resData, key)) {
    //     const element = resData[key];
    //     dataLists.push({
    //       name: formatStateTime(key),
    //       value: resData[key],
    //     });
    //   }
    // }
}
// 获取前几天的时间
function timeCalculation(dates, param, daynum = 1) {
    let dayNow = "";
    let dayNowin = "";
    let date = Date.parse(dates);
    var resulttime = null
    if (param == "add") {
        resulttime = new Date(date + 24 * 60 * 60 * 1000 * daynum);
    } else if (param == "subtract") {
        resulttime = new Date(date - 24 * 60 * 60 * 1000 * daynum);
    }
    dayNowin = resulttime.getFullYear() + "年" + (resulttime.getMonth() + 1) + "月" + resulttime.getDate() + '日';
    let m = (resulttime.getMonth() + 1) < 10 ? '0' + (resulttime.getMonth() + 1) : (resulttime.getMonth() + 1)
    let d = resulttime.getDate() < 10 ? '0' + resulttime.getDate() : resulttime.getDate()
    dayNow = resulttime.getFullYear() + "-" + m + "-" + d;
    return dayNow

}
/**
 * 获取本月、上月、下月的起始日、结束日 (不传或0代表本月，-1代表上月，1代表下月)
 * 1.调用方法 getMonth("start",0)、getMonth("end",0)
 * 2.type 为"start"代表开始日期, type为"end"代表结束日期
 * 3.months 不传或0代表本月，-1代表上月，1代表下月
 * @param {Object} type
 * @param {Object} months
 */
function formatCurrentMonth(type, months) {
    var d = new Date();
    var year = d.getFullYear();
    var month = d.getMonth() + 1;
    if (Math.abs(months) > 12) {
        months = months % 12;
    };
    if (months != 0) {
        if (month + months > 12) {
            year++;
            month = (month + months) % 12;
        } else if (month + months < 1) {
            year--;
            month = 12 + month + months;
        } else {
            month = month + months;
        };
    };
    month = month < 10 ? "0" + month : month;
    var date = d.getDate();
    var firstday = year + "-" + month + "-" + "01";
    var lastday = "";
    if (month == "01" || month == "03" || month == "05" || month == "07" || month == "08" || month == "10" || month ==
        "12") {
        lastday = year + "-" + month + "-" + 31;
    } else if (month == "02") {
        if ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) {
            lastday = year + "-" + month + "-" + 29;
        } else {
            lastday = year + "-" + month + "-" + 28;
        };
    } else {
        lastday = year + "-" + month + "-" + 30;
    };
    var day = "";
    if (type == "start") {
        day = firstday;
    } else {
        day = lastday;
    };
    return day;
}
/**
 * 获取两个时间短之前的日期数组
 * @param {string} starDay
 * @param {string} endDay
 */
function getDayAll(starDay, endDay) {
    var arr = [];
    var dates = [];
    // 设置两个日期UTC时间
    var db = new Date(starDay);
    var de = new Date(endDay);

    // 获取两个日期GTM时间
    var s = db.getTime() - 24 * 60 * 60 * 1000;
    var d = de.getTime() - 24 * 60 * 60 * 1000;

    // 获取到两个日期之间的每一天的毫秒数
    for (var i = s; i <= d;) {
        i = i + 24 * 60 * 60 * 1000;
        arr.push(parseInt(i))
    }
    // 获取每一天的时间  YY-MM-DD
    for (var j in arr) {
        var time = new Date(arr[j]);
        var year = time.getFullYear(time);
        var mouth = (time.getMonth() + 1) >= 10 ? (time.getMonth() + 1) : ('0' + (time.getMonth() + 1));
        var day = time.getDate() >= 10 ? time.getDate() : ('0' + time.getDate());
        var YYMMDD = year + '-' + mouth + '-' + day;
        dates.push(YYMMDD)
    }
    return dates
}
//获取两个时间段之间的月份
function getYearAndMonth(start, end) {
    var result = [];
    var starts = start.split('-');
    var ends = end.split('-');
    var staYear = parseInt(starts[0]);
    var staMon = parseInt(starts[1]);
    var endYear = parseInt(ends[0]);
    var endMon = parseInt(ends[1]);
    while (staYear <= endYear) {
        if (staYear === endYear) {
            while (staMon < endMon) {
                staMon++;
                var str = staYear + '-' + (staMon >= 10 ? staMon : '0' + staMon);
                result.push(str);
            }
            staYear++;
        } else {
            staMon++;
            if (staMon > 12) {
                staMon = 1;
                staYear++;
            }
            var str = staYear + '-' + (staMon >= 10 ? staMon : '0' + staMon);
            result.push(str);
        }
    }
    result.unshift(start)
    return result;
}
//获取当前月最后一天日期
function getLastDay(year, month) {
    var new_year = year; //取当前的年份
    var new_month = month++; //取下一个月的第一天，方便计算（最后一天不固定）
    if (month > 12) {
        new_month -= 12; //月份减
        new_year++; //年份增
    }
    var new_date = new Date(new_year, new_month, 1); //取当年当月中的第一天
    return (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate(); //获取当月最后一天日期
}

//小写数字转换大写数字
function Arabia_To_SimplifiedChinese(Num) {
    for (var i = Num.length - 1; i >= 0; i--) {
        Num = Num.replace(',', ''); // 替换Num中的“,”
        Num = Num.replace(' ', ''); // 替换Num中的空格
    }
    if (isNaN(Num)) {
        // 验证输入的字符是否为数字
        // alert("请检查小写金额是否正确");
        return;
    }
    // 字符处理完毕后开始转换，采用前后两部分分别转换
    let part = String(Num).split('.');
    let newchar = '';
    // 小数点前进行转化
    for (i = part[0].length - 1; i >= 0; i--) {
        if (part[0].length > 10) {
            // alert("位数过大，无法计算");
            return '';
        } // 若数量超过拾亿单位，提示
        let tmpnewchar = '';
        let perchar = part[0].charAt(i);
        switch (perchar) {
            case '0':
                tmpnewchar = '零' + tmpnewchar;
                break;
            case '1':
                tmpnewchar = '一' + tmpnewchar;
                break;
            case '2':
                tmpnewchar = '二' + tmpnewchar;
                break;
            case '3':
                tmpnewchar = '三' + tmpnewchar;
                break;
            case '4':
                tmpnewchar = '四' + tmpnewchar;
                break;
            case '5':
                tmpnewchar = '五' + tmpnewchar;
                break;
            case '6':
                tmpnewchar = '六' + tmpnewchar;
                break;
            case '7':
                tmpnewchar = '七' + tmpnewchar;
                break;
            case '8':
                tmpnewchar = '八' + tmpnewchar;
                break;
            case '9':
                tmpnewchar = '九' + tmpnewchar;
                break;
        }
        switch (part[0].length - i - 1) {
            case 0:
                tmpnewchar = tmpnewchar;
                break;
            case 1:
                if (perchar != 0) tmpnewchar = tmpnewchar + '十';
                break;
            case 2:
                if (perchar != 0) tmpnewchar = tmpnewchar + '百';
                break;
            case 3:
                if (perchar != 0) tmpnewchar = tmpnewchar + '千';
                break;
            case 4:
                tmpnewchar = tmpnewchar + '万';
                break;
            case 5:
                if (perchar != 0) tmpnewchar = tmpnewchar + '十';
                break;
            case 6:
                if (perchar != 0) tmpnewchar = tmpnewchar + '百';
                break;
            case 7:
                if (perchar != 0) tmpnewchar = tmpnewchar + '千';
                break;
            case 8:
                tmpnewchar = tmpnewchar + '亿';
                break;
            case 9:
                tmpnewchar = tmpnewchar + '十';
                break;
        }
        newchar = tmpnewchar + newchar;
    }
    //替 换所有无用汉字，直到没有此类无用的数字为止
    while (newchar.search('零零') != -1 || newchar.search('零亿') != -1 || newchar.search('亿万') != -1 || newchar.search(
            '零万') != -1) {
        newchar = newchar.replace('零亿', '亿');
        newchar = newchar.replace('亿万', '亿');
        newchar = newchar.replace('零万', '万');
        newchar = newchar.replace('零零', '零');
    }
    // 替换以“一十”开头的，为“十”
    if (newchar.indexOf('一十') == 0) {
        newchar = newchar.substr(1);
    }
    // 替换以“零”结尾的，为“”
    if (newchar.lastIndexOf('零') == newchar.length - 1) {
        newchar = newchar.substr(0, newchar.length - 1);
    }
    return "第" + newchar + "班";
}

function formatArrayToObject() {}

export {
    buildDateAxis,
    buildLinkSelect,
    initUserInfo,
    getRoleId,
    isNull,
    isNumber,
    isObject,
    isString,
    isArray,
    isSymbol,
    formatPictureIds,
    filterSelectLists,
    formatObjectToObject,
    formatArrayToObject,
    timeCalculation,
    formatCurrentMonth,
    getDayAll,
    getYearAndMonth,
    getLastDay,
    Arabia_To_SimplifiedChinese

};